<template>
	<view class="container">
		<uni-forms ref="form" :value="formData" err-show-type="toast">
			<uni-forms-item name="email" :label="$w('新邮箱')">
				<uni-easyinput :placeholder="$w('请输入新邮箱')" :focus="focus" v-model="formData.email" trim="both"
					:inputBorder="false" :key="key" />
			</uni-forms-item>
			<uni-forms-item name="code">
				<uni-id-pages-email-form ref="shortCode" :email="formData.email" type="register"
					v-model="formData.code">
				</uni-id-pages-email-form>
			</uni-forms-item>

			<view class="note-box" style="padding-top: 100rpx;">
				<text>{{$w('设置后，将用于登录、接收信息等，具有唯一性。')}}</text>
			</view>
			<!-- <view class="">
				<button type="default" @click="test">test </button>
			</view> -->
			<view class="uni-button-group">
				<button type="primary" class="uni-button" @click="submit">{{$w('提交')}}</button>
			</view>
		</uni-forms>
		<uv-toast-wjf ref="uvToastWjf"></uv-toast-wjf>
		<uv-modal ref="uvModal" :title="uvModelParam.title" :content='uvModelParam.content' :align="uvModelParam.align"
			:confirmText="uvModelParam.confirmText" :cancelText="uvModelParam.cancelText"
			:showCancelButton="uvModelParam.showCancelButton"></uv-modal>
	</view>
</template>

<script>
	import commMixinWjf from '@/common/mixin/common-mixin-wjf.js'
	// import rules from './validator.js';
	import mixinRules from './mixin-rules';
	import {
		mutations as uniIdMutations
	} from '@/uni_modules/uni-id-pages/common/store.js';
	const db = uniCloud.database();
	const uniIdCo = uniCloud.importObject("uni-id-co", {
		errorOptions: {
			type: 'toast'
		}
	})
	const wjfCo = uniCloud.importObject('wjf-co', {
		customUI: false,
		loadingOptions: {
			title: '', // 只保留转圈状态
		},
		errorOptions: {
			type: 'toast'
		}
	})
	import i18nMixin from '../i18n/i18n-mixin.js'
	export default {
		mixins: [commMixinWjf, i18nMixin, mixinRules],
		data() {
			return {
				formData: {
					email: "",
					code: '',
					type: 'login',
					"captcha": ""
				},
				focus: true,
				key: 0,
				isSubmit: false,
				sendedCode: '', //发送的验证码
				accountInfo: null,
			}
		},
		async onLoad() {
			// await uniIdCo.getAccountInfo().then(res => {
			// 	this.accountInfo = res
			// 	console.log('onLoad', this.accountInfo);
			// })

		},
		computed: {},
		onShow() {
			// console.log('onShow');
		},
		onReady() {
			if (this.formData.email) {
				this.$refs.shortCode.start();
			}
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			test() {
				this.$uvToastWjf({
					message: 'test'
				}, () => {
					console.log('55668');
				})
				// this.$uvModal({
				// 	content: "确定变更邮箱？",
				// 	align: 'center',
				// 	showCancelButton: true
				// }, () => {
				// 	console.log('tt555666');
				// })
				// const wjfCo=uniCloud.importObject('wjf-co')
				// wjfCo.findUsedEmail({
				// 	email:'wjf5866@163.com'
				// }).then(res=>{
				// 	console.log(res);
				// })
			},
			async testApi() {
				// const obj = uniCloud.importObject('uni-id-co')
				// await obj.replaceEmail().then(res => {
				// 	console.log(res);
				// })
				await db.collection('uni-id-users').where(`'email' == 'wjf5866@gmail.com'`).field('email').get().then(
					res => {
						console.log(res);
					})
			},
			submit() {
				// console.log(this.formData);
				this.$refs.form.validate().then(res => {
					this.submitForm(res)
				})
			},
			async submitForm(params) {
				if (this.formData.email == this.userInfo.email) {
					this.$uvToastWjf({
						message: this.$w("邮箱未变更"),
						type: 'error'
					}, () => {
						this.formData.code = ''
						this.$refs.shortCode.$refs.captcha.getImageCaptcha(false)
						this.$refs.shortCode.clearCaptcha()
					})
					return
				}
				let res = await wjfCo.findUsedEmail({
					email: this.formData.email
				})
				if (res.usedNum > 0) {
					this.$uvToastWjf({
						message: this.$w('此邮箱已被使用，请更换')
					}, () => {
						this.formData.email = ''
						this.formData.code = ''
						this.$refs.shortCode.$refs.captcha.getImageCaptcha(false)
						this.$refs.shortCode.clearCaptcha()
					})
					return
				} else {
					// console.log(this.formData.name);
					this.update()
				}
			},

			update() {
				let newUserInfo = Object.assign({}, this.userInfo, {
					email: this.formData.email
				})

				this.$uvModal({
					content: this.$w("确定变更邮箱？"),
					align: 'center',
					showCancelButton: true
				}, () => {
					let {
						email,
						code
					} = this.formData
					uniIdCo.replaceEmail({
						email,
						code,
						uid: this.userInfo._id
					}).then(res => {
						this.$uvToastWjf({
							message: this.$w("变更成功"),
							type: 'success'
						})
						this.navTimeBack();
						uniIdMutations.setUserInfo(newUserInfo)
					}).catch(err => {
						// console.log('报错');
					})
				})
			},
		}
	}
</script>

<style lang="scss">
	.container {
		max-width: 800px;
		height: 100vh;
		/* 设置最大宽度 */
		margin: 0 auto;
		/* 居中显示 */
		// padding: 20px;
		/* 添加内边距（可选） */
		background-color: rgba(240, 240, 240, 1);
	}

	.uni-button-group {
		position: fixed;
		bottom: calc(var(--window-bottom) + 40rpx);
		left: 70rpx;
		right: 70rpx;
		display: flex;

		// .uni-button {
		// 	flex: 1;
		// }
	}

	.uni-forms .uni-forms-item {
		background: #fff;
		padding: 6rpx;
		padding-left: 22rpx;
	}

	.note-box {
		padding: 20px;
		color: #555;
	}
</style>